#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# ======================================================
# @File:      : excel_utils
# @Author     : forward_huan
# @Date       : 2025/5/26 20:31
# @Desc       :
# ======================================================
from typing import List

from openpyxl import load_workbook, Workbook
from openpyxl.worksheet.worksheet import Worksheet

from ...common.utils.io_utils import closeStream


def read_excel(file_path, sheet_name: str = None):
    """
    读取excel表格的数据

    :param file_path: excel文件名称
    :param sheet_name: sheet名
    :return:
    """
    wb = load_workbook(file_path)
    if sheet_name is None:
        sheet: Worksheet = wb.active
    else:
        sheet: Worksheet = wb[sheet_name]
    result = []
    for row in range(1, sheet.max_row + 1):
        result.append([sheet.cell(row, col).value for col in range(1, sheet.max_column + 1)])
    closeStream(wb)
    return result


def get_sheet_names(file_path):
    """
    获取sheet名称

    :param file_path:
    :return:
    """
    # noinspection PyBroadException
    try:
        wb = load_workbook(file_path)
        result = wb.sheetnames
        closeStream(wb)
        return result
    except Exception:
        return []


def write_excel(file_path, data: List[List[object]], sheet_name=None):
    """
    写入excel

    :param file_path: 写入路径
    :param data: 写入数据
    :param sheet_name: sheet名
    :return:
    """
    wb = Workbook()
    if sheet_name is None:
        sheet: Worksheet = wb.active
    else:
        sheet: Worksheet = wb.create_sheet(sheet_name, len(wb.sheetnames))
    for row_data in data:
        sheet.append(row_data)
    wb.save(file_path)
    closeStream(wb)
